<template>
  <div class="monitorCdrpeer">
    <affix :label="$t('monitor.seatStateLogSearch')"></affix>
    <el-form label-position="left" label-width="80px">
      <el-form-item :label="$t('public.agent')">
        <!-- <el-select v-model="form.selectedAgent" filterable :placeholder="$t('public.pleasePick')">
          <el-option
            :label="$t('public.all')"
            value="">
          </el-option>
          <el-option
            v-for="item in agents"
            :label="item.displayName + '[' + item.exten + ']'"
            :key="item._id"
            :value="item._id">
          </el-option>
        </el-select> -->
        <m7Select class="m7-select" filterable :options="selectAgents" v-model="form.selectedAgent"></m7Select>
        <el-checkbox v-model="form.includeSubordinate" style="margin-left: 20px;">{{$t('monitor.includeSeatSubordinate')}}</el-checkbox>
      </el-form-item>
      <el-form-item :label="$t('monitor.bAndETime')">
        <el-date-picker size="mini"
                        class="date-choose"
                        v-model="form.date"
                        :id="['monitorDate1','monitorDate2']"
                        type="datetimerange"
                        :editable="false"
                        :picker-options="pickerOptions2"
                        :placeholder="$t('sms.choTimeScope')"
                        align="right">
        </el-date-picker>
        <el-checkbox v-model="form.StartingAndEndingTime" @change="startAndEndChange" style="margin-left: 20px;">{{$t('monitor.showLoginAndExitTime')}}</el-checkbox>
      </el-form-item>
    </el-form>
    <div class="btn-wrap">
      <el-button class="primary_btn report_excel_btn" @click.stop="resetForm">{{$t('public.reset')}}</el-button>
      <el-button type="primary" class="primary_btn" @click.stop="searchCdrpeer">{{$t('public.search2')}}</el-button>
    </div>
    <affix :label="$t('monitor.seatStateLogSearchResult')"></affix>
    <div class="btn-wrap">
      <el-button type="primary" class="primary_btn" @click.stop="exportCdrPeer">{{$t('report.exportXls')}}</el-button>
      <el-button v-if="!form.StartingAndEndingTime" type="primary" class="primary_btn export-detail" @click.sotp="exportDetailCdrPeer">{{$t('monitor.expoltDetailEXCEL')}}</el-button>
    </div>
    <!--下边表格展示============================================-->
    <div class="tables">
      <div class="caption">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="curPage"
          :count="count"
          @turnPage="handleCurrentChange"
          :totalPage="Math.ceil(count/pageSize)"
        >
        </Pagination>
      </div>
      <!--表格===============================================-->
      <el-table v-if="!form.StartingAndEndingTime" :data="tableData" stripe style="width: 100%" v-loading="tableLoading" size="mini">
        <el-table-column prop="agentName" :label="$t('public.agent')"></el-table-column>
        <el-table-column prop="EXTEN_TYPE_NAME" :label="$t('monitor.loginType')"></el-table-column>
        <el-table-column prop="BEGIN_TIME" :label="$t('monitor.loginTime')"></el-table-column>
        <el-table-column prop="END_TIME" :label="$t('monitor.signOutTime')"></el-table-column>
        <el-table-column prop="onLineTime" :label="$t('monitor.onlineTime')"></el-table-column>
        <el-table-column prop="busyTimeLen" :label="$t('monitor.busyTime')"></el-table-column>
        <el-table-column prop="BUSYTYPE" :label="$t('monitor.busyType')"></el-table-column>
        <el-table-column prop="COMMENTS_NAME" :label="$t('monitor.signOutReason')"></el-table-column>
        <el-table-column  :label="$t('sms.operate')" width="100">
          <template scope="scope">
             <!--忙碌时长不为0或者是结束时间不为空时，有查看按钮-->
            <el-button v-if="tableData[scope.$index].busyTimeLength !== 0 || tableData[scope.$index].END_TIME === null" type="text" @click.stop="showDetail(scope.$index, tableData)" size="small">{{$t('sms.searchToLook')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table v-if="form.StartingAndEndingTime" :data="tableData" stripe style="width: 100%" v-loading="tableLoading" size="mini">
        <el-table-column prop="agentName" :label="$t('public.agent')"></el-table-column>
        <el-table-column prop="BEGIN_TIME" :label="$t('monitor.loginTime')"></el-table-column>
        <el-table-column prop="END_TIME" :label="$t('monitor.signOutTime')"></el-table-column>
      </el-table>
      <!--表格==============================================================================-->
      <!--点击查看  dialog 短信详情    start  ===============================================-->
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('monitor.agentStateDetailInfo')" :visible.sync="dialogCdrpeerDetailVisible" width="50%">
        <div class="shuomin">
          <strong>{{$t('monitor.tip')}}</strong>{{$t('monitor.tipContent')}}
        </div>
        <div class="caption">
          <Pagination
            class="fr"
            :small="true"
            :currentPage="pageForDetail"
            :count="countForDetail"
            @turnPage="handleCurrentDetail"
            :totalPage="Math.ceil(countForDetail/pageSize)"
          >
          </Pagination>
        </div>
        <!--表格===============================================-->
        <el-table v-if="!form.StartingAndEndingTime" :data="tableDataForDetail" stripe style="width: 100%" v-loading="tableLoading" size="mini">
          <el-table-column prop="agentName" :label="$t('public.agent')"></el-table-column>
          <el-table-column prop="EXTEN_TYPE_NAME" :label="$t('monitor.loginType')"></el-table-column>
          <el-table-column prop="BEGIN_TIME" :label="$t('monitor.beginTime')"></el-table-column>
          <el-table-column prop="END_TIME" :label="$t('monitor.endTime')"></el-table-column>
          <el-table-column prop="busyTimeLen" :label="$t('monitor.stateTime')"></el-table-column>
          <el-table-column prop="BUSY_TYPE_NAME" :label="$t('monitor.state')"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click.stop="dialogCdrpeerDetailVisible = false">{{$t('sms.close')}}</el-button>
        </div>
      </el-dialog>
      <!--点击查看  dialog 短信详情    end   ===============================================-->
    </div>
  </div>
</template>
<script>
  import affix from './../../ui-modules/affix/Affix.vue'
  import {getFormatDateTime, deepClone, getCallTimeLength} from '@/utils/m7Utils.js'
  import Pagination from '@/components/public-modules/card/Pagination'
  export default {
    name: 'MonitorCdrpeer',
    data () {
      return {
        agents: [],
        phoneBars: [],
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        form: {
          selectedAgent: '',
          includeSubordinate: false,
          date: [],
          StartingAndEndingTime: false
        },
        y: '',
        m: '',
        d: '',
        queryArry: '',
        tableLoading: false,
        tableData: [],
        tableDataForDetail: [],
        count: 0,
        pageSize: 10,
        curPage: 1,
        pageForDetail: 1,
        countForDetail: 0,
        dialogCdrpeerDetailVisible: false,
        BEGIN_TIME_DETAIL: '',
        END_TIME_DETAIL: '',
        AGENT_DETAIL: ''
      }
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return  this.agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
      }
    },
    methods: {
      searchCdrpeer () {
        this.curPage = 1
        this.search()
      },
      handleCurrentChange (val) {
        this.curPage = val
        this.search()
      },
      startAndEndChange () {
        this.searchCdrpeer()
      },
      resetForm () {
        this.form.selectedAgent = ''
        this.form.date = [new Date(this.y, this.m, this.d), new Date(this.y, this.m, this.d, 23, 59, 59)]
        this.form.includeSubordinate = false
        this.form.StartingAndEndingTime = false
      },
      search () {
        let data = {}
        data = deepClone(this.form)
        if (data.date) {
          if (data.date[0]) {
            data.BEGIN_TIME = getFormatDateTime(data.date[0])
          }
          if (data.date[1]) {
            data.END_TIME = getFormatDateTime(data.date[1])
          }
        }
        data.page = this.curPage
        data.pageSize = this.pageSize
        data.AGENT = this.form.selectedAgent
        data.reportType = 'call_report_agent'
        data.ACTION_TYPE = 'login'
//        勾选 显示座席下架  座席不能为空
        if (data.includeSubordinate && data.AGENT === '') {
          this.$message.error(this.$t('monitor.inputAgentNoToSearch'))
          return
        }
//        座席没有匹配上  给出提示
        let flag = false
        this.agents.forEach(item => {
          if (item._id === data.AGENT || data.AGENT === '') {
            flag = true
          }
        })
        if (!flag) {
          this.$message.error(this.$t('monitor.agentFail'))
          return
        }
//        开始时间或者结束时间不能为空
        if (!data.BEGIN_TIME || !data.END_TIME) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        }
        console.log(data)
        this.tableLoading = true
        this.$store.dispatch('queryCdrPeer', data).then(res => {
          if (res.success) {
            if (res.queryArry) {
              this.queryArry = res.queryArry.join(',')
            } else {
              this.queryArry = ''
            }
            this.tableLoading = false
            let tableData = res.list || []
            this.count = res.count
            tableData.forEach(item => {
//              处理座席名称
              this.agents.forEach(one => {
                if (data.StartingAndEndingTime) {
                  if (item._id === one._id) {
                    item.agentName = one.displayName + '[' + one.exten + ']'
                  }
                } else {
                  if (item.AGENT === one._id) {
                    item.agentName = one.displayName + '[' + one.exten + ']'
                  }
                }
              })
//              登录方式
              if (item.EXTEN_TYPE === 'Local') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.phone')
              } else if (item.EXTEN_TYPE === 'gateway') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.wangguan')
              } else if (item.EXTEN_TYPE === 'sip') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.softPhone')
              } else if (item.EXTEN_TYPE === 'none') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.noPhone')
              }
//              签出原因
              if (item.COMMENTS === 'reserve') { // 离线接听
                item.COMMENTS_NAME = this.$t('monitor.outlineHold')
              } else if (item.COMMENTS === 'Timeout') { // 超时 (直接关闭浏览器1-2分钟后再登录，或者是电话条轮询请求超过1分钟后)
                item.COMMENTS_NAME = this.$t('monitor.outTime')
              } else if (item.COMMENTS === 'akick') { // 管理员签出
                item.COMMENTS_NAME = this.$t('monitor.adminOut')
              } else if (item.COMMENTS === 'ukick') { // 重复登录（直接关闭浏览器1分钟之内再登录，或者是互踢）
                item.COMMENTS_NAME = this.$t('monitor.loginAgain')
              } else if (item.COMMENTS === 'ReserveAutoSignedOut') { // 自动签出
                item.COMMENTS_NAME = this.$t('monitor.automaticCheckout')
              } else if (item.COMMENTS === null) {
                item.COMMENTS_NAME = ''
              } else { // 正常
                item.COMMENTS_NAME = this.$t('monitor.normal')
              }
//              忙碌时长
              if (item.busyTimeLength === 0) {
                item.busyTimeLen = '00:00:00'
              } else {
                item.busyTimeLen = getCallTimeLength(item.busyTimeLength / 1000)
              }
//              在线时长
              let beginTime = item.BEGIN_TIME
              let endTime = item.END_TIME
              if (beginTime === null || endTime === null || beginTime === undefined || endTime === undefined) {
                item.onLineTime = '00:00:00'
              } else {
                let begin = new Date(Date.parse(beginTime.replace(/-/g, '/')))
                let end = new Date(Date.parse(endTime.replace(/-/g, '/')))
                let time = end.getTime() - begin.getTime()
                item.onLineTime = getCallTimeLength(time / 1000)
              }
              // 登录状态
              if (item.BUSY_TYPE === '-1') {
                item.BUSYTYPE = this.$t('monitor.offline')
              } else {
                item.BUSYTYPE = this.$t('monitor.online')
              }
            })
            this.tableData = tableData
          }
        })
      },
      exportCdrPeer () {
        let Query = {}
        Query.AGENT = this.form.selectedAgent
        Query.selectedAgent = this.form.selectedAgent
        Query.includeSubordinate = this.form.includeSubordinate
        Query.StartingAndEndingTime = this.form.StartingAndEndingTime
        let BEGIN, END
        if (this.form.date) {
          if (this.form.date[0]) {
            BEGIN = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            END = getFormatDateTime(this.form.date[1])
          }
        }
        //        开始时间或者结束时间不能为空
        if (!BEGIN || !END) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        }
        Query.BEGIN_TIME = {'$gte': BEGIN, '$lte': END}
        Query.END_TIME = END
        Query.reportType = 'call_report_agent'
        Query.queryArry = this.queryArry
        Query.accountId = this.$store.state.session.user.account
        Query.dataDB = this.$store.state.session.account.dataDB
        // Query.ASTERISK = this.$store.state.session.user.pbx
        Query.ACTION_TYPE = 'login'
        let data = {}
        data.Method = 'exportCdrPeer'
        data.Query = Query
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      exportDetailCdrPeer () {
        let BEGIN, END
        if (this.form.date) {
          if (this.form.date[0]) {
            BEGIN = getFormatDateTime(this.form.date[0])
          }
          if (this.form.date[1]) {
            END = getFormatDateTime(this.form.date[1])
          }
        }
        //        开始时间或者结束时间不能为空
        if (!BEGIN || !END) {
          this.$message.error(this.$t('monitor.timeWrongTip'))
          return
        } else if (BEGIN.substring(0, 10) !== END.substring(0, 10)) {
          this.$message.error(this.$t('monitor.timeTip'))
          return
        }
        let Query = {}
        Query.BEGIN_TIME = {'$gte': BEGIN, '$lte': END}
        Query.END_TIME = END
        Query.AGENT = this.form.selectedAgent
        Query.selectedAgent = this.form.selectedAgent
        Query.includeSubordinate = this.form.includeSubordinate
        Query.StartingAndEndingTime = this.form.StartingAndEndingTime
        Query.reportType = 'call_report_agent'
        Query.queryArry = this.queryArry
        Query.accountId = this.$store.state.session.user.account
        Query.dataDB = this.$store.state.session.account.dataDB
        // Query.ASTERISK = this.$store.state.session.user.pbx
        Query.ACTION_TYPE = 'login'
        Query.type = 'ReportCdrPeerExport'
        Query.user = this.$store.state.session.user._id
        Query.userType = this.$store.state.session.user.type
        let data = {}
        data.Method = 'exportCdrPeerDetail'
        data.Query = Query
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      searchDetail () {
        let data = {}
        data.BEGIN_TIME = this.BEGIN_TIME_DETAIL
        data.END_TIME = this.END_TIME_DETAIL
        data.AGENT = this.AGENT_DETAIL
        data.ACTION_TYPE = 'busy'
        data.pageSize = this.pageSize
        data.page = this.pageForDetail
        this.$store.dispatch('queryCdrPeer', data).then(res => {
          if (res.success) {
            let tableData = res.list || []
            this.countForDetail = res.count
            tableData.forEach(item => {
//              处理座席名称
              this.agents.forEach(one => {
                if (data.StartingAndEndingTime) {
                  if (item._id === one._id) {
                    item.agentName = one.displayName + '[' + one.exten + ']'
                  }
                } else {
                  if (item.AGENT === one._id) {
                    item.agentName = one.displayName + '[' + one.exten + ']'
                  }
                }
              })
//              登录方式
              if (item.EXTEN_TYPE === 'Local') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.phone')
              } else if (item.EXTEN_TYPE === 'gateway') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.wangguan')
              } else if (item.EXTEN_TYPE === 'sip') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.softPhone')
              } else if (item.EXTEN_TYPE === 'none') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.noPhone')
              }
//              忙碌时长
              if (item.END_TIME && item.BEGIN_TIME) {
                item.busyTimeLen = getCallTimeLength(item.TIME_LENGTH)
              } else {
                item.busyTimeLen = ''
              }
//              状态
              this.phoneBars.forEach(one => {
                if (item.BUSY_TYPE === '99') {
                  item.BUSY_TYPE_NAME = this.$t('monitor.autoBusy')
                } else if (item.BUSY_TYPE === '98') {
                  item.BUSY_TYPE_NAME = this.$t('monitor.postProcessing')
                } else if (item.BUSY_TYPE === '97') {
                  item.BUSY_TYPE_NAME = this.$t('cti.dialing')
                } else if (item.BUSY_TYPE === one.PhoneBarItemId) {
                  item.BUSY_TYPE_NAME = one.PhoneBarItemName
                }
              })
            })
            this.tableDataForDetail = tableData
          }
        })
      },
      handleCurrentDetail (val) {
        this.pageForDetail = val
        this.searchDetail()
      },
      showDetail (index, rows) {
        this.dialogCdrpeerDetailVisible = true
        this.pageForDetail = 1
        this.BEGIN_TIME_DETAIL = rows[index].BEGIN_TIME
        this.END_TIME_DETAIL = rows[index].END_TIME || 'null'
        this.AGENT_DETAIL = rows[index].AGENT
        this.searchDetail()
      }
    },
    components: {
      affix,
      Pagination
    },
    beforeMount () {
      this.y = new Date().getFullYear()
      this.m = new Date().getMonth()
      this.d = new Date().getDate()
      this.form.date = [new Date(this.y, this.m, this.d), new Date(this.y, this.m, this.d, 23, 59, 59)]
      let p1 = this.$store.dispatch('getCache', {type: 'agents'})
      let p2 = this.$store.dispatch('getCache', {type: 'phoneBars'})
      Promise.all([p1, p2]).then(([res1, res2]) => {
        this.agents = res1
        this.phoneBars = res2
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .monitorCdrpeer
    padding 20px
    .m7-select
      width 200px
    .ui-affix
      padding-bottom 0
    .btn-wrap
      padding 20px
      text-align right
      .export-detail
        margin-left 20px
    .caption
      color $c-prompt
      height 48px
      line-height 48px
      padding-left 14px
      border 1px solid #ddd
      border-bottom none
      .fr
        padding-top 10px
        height 38px
  .shuomin
    color: $c-prompt;
    margin-bottom: 20px;
</style>
